package service

import (
	"appshop/app/admin/models"
	"appshop/app/admin/service/dto"
	"appshop/commons/db"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"time"
)

func Insert(ma models.App) (interface{}, error) {
	r, err := db.Db.Exec(
		"insert into as_app(bundle_id,`desc`,name,path,version,icon,add_time)values (?,?,?,?,?,?,?)",
		ma.PackageBundleId,
		ma.PackageDesc,
		ma.PackageName,
		ma.PackagePath,
		ma.PackageVersion,
		ma.PackageIcon,
		time.Now(),
	)
	if err != nil {
		// fmt.Println("exec failed, ", err)
		return nil, err
	}
	id, err := r.LastInsertId()
	if err != nil {
		// fmt.Println("exec failed, ", err)
		return nil, err
	}

	// fmt.Println("insert success: ", id)
	return id, nil
	// defer Db.Close()
}

// GetById 根据id查询
func GetById(id int64) (interface{}, error) {
	var app models.App
	err := db.Db.Get(&app,
		"select id, bundle_id,`desc`, name, path, version,icon, add_time  from as_app where id = ?", id,
	)
	if err != nil {
		// fmt.Println("exec failed, ", err)
		return nil, err
	}
	// fmt.Printf("查询结果：%#v\n", app)
	appDetails := dto.Generate(app)
	return appDetails, nil
}

// CheckExists 根据包名和版本号查重
func CheckExists(bundleId string, version string) (bool, error) {
	total := new(int)
	err := db.Db.Get(&total,
		"select count(*) from as_app where bundle_id = ? and version = ?", bundleId, version,
	)
	if err != nil {
		// fmt.Println("exec failed, ", err)
		return false, err
	}
	if *total > 0 {
		// fmt.Println("已存在相同的应用包")
		return true, nil
	}
	// fmt.Printf("查询结果：%#v\n", *total)
	return false, nil
}

// GetList 查询应用列表，支持搜索和排序
func GetList(appSearch dto.AppSearch) ([]models.App, error) {
	// 将请求模型转换成dto对象

	var apps []models.App
	var sqlStr strings.Builder
	var args []interface{}
	sqlStr.WriteString("select id, bundle_id, name, `desc`, path, version, icon, add_time from as_app where 1=1 ")
	// 按照名称查询
	if appSearch.PackageName != "" {
		sqlStr.WriteString("and name = ?")
		args = append(args, appSearch.PackageName)
	}
	// 按照包名查询
	// if appSearch.PackageBundleId != "" {
	// 	sqlStr.WriteString("and bundle_id = ?")
	// 	args = append(args, appSearch.PackageBundleId)
	// }
	// 按照版本号查询
	// if appSearch.PackageVersion != "" {
	// 	sqlStr.WriteString("and version = ")
	// 	args = append(args, appSearch.PackageVersion)
	// }
	sqlStr.WriteString(" order by bundle_id, add_time desc")
	// fmt.Println("查询sql, ", sqlStr.String())
	err := db.Db.Select(&apps, sqlStr.String(), args...)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return nil, err
	}
	// fmt.Printf("查询结果：%#v\n", apps)
	return apps, nil
}

func GetAppMenu(appSearch dto.AppSearch) ([]dto.AppCollection, error) {
	var appCollectionResult []dto.AppCollection

	// 构建一个应用的当前app和历史版本
	// var appCollection dto.AppCollection
	// 查询到所有的app记录
	apps, err := GetList(appSearch)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return nil, err
	}
	// 构建一个应用的当前app和历史版本
	var appHistory []dto.AppDetails
	var currentApp dto.AppDetails
	for _, app := range apps {
		// 暂存当前的记录
		if currentApp == (dto.AppDetails{}) {
			currentApp = dto.Generate(app)
			appHistory = append(appHistory, dto.Generate(app))
			continue
		}
		if currentApp.PackageBundleId == app.PackageBundleId {
			appHistory = append(appHistory, dto.Generate(app))
		} else {
			// 归档同一个bundleId的记录
			appCollectionResult = append(appCollectionResult, dto.AppCollection{
				CurrentApp: currentApp,
				History:    appHistory,
			})
			// 清空已归档记录
			appHistory = nil
			// 继续新的bundle
			currentApp = dto.Generate(app)
			appHistory = append(appHistory, dto.Generate(app))
		}
	}

	// 如果值不为空，处理
	if currentApp != (dto.AppDetails{}) && appHistory != nil {
		appCollectionResult = append(appCollectionResult, dto.AppCollection{
			CurrentApp: currentApp,
			History:    appHistory,
		})
	}

	return appCollectionResult, nil
}
